<template>
  <div class="container">
    <div class="trigger" @click="trigger">
      <div v-if="img" class="preview">
        <NImage
          :src="getFullImgPath(img.path)"
          :alt="img.path"
          :width="size"
          :height="size"
          :preview-disabled="true"
        />
      </div>

      <div v-else class="cross">
        <div class="bar vertical"></div>
        <div class="bar horizontal"></div>
      </div>
    </div>

    <input
      ref="inputRef"
      type="file"
      @change="fileHandler"
      style="display: none"
    />
  </div>
</template>

<script setup lang="ts">
import { Picture } from "@/api/octp/models/picture";
import { getPictureById, pictureUpload } from "@/api/octp/routes/picture";
import { useMessage } from "@/hooks/message";
import { getFullImgPath } from "@/utils/constants";
import { computed, ref, watchEffect } from "vue";

export interface ZRadioGroupProps {
  value: any;
  type?: any;
  size?: number;
  disabled?: boolean;
}
const props = withDefaults(defineProps<ZRadioGroupProps>(), {
  type: "Photo",
  size: 120,
});
const sizePx = computed(() => props.size + "px");

const emit = defineEmits<{
  (e: "update:value", value: any): void;
}>();
const updateValue = (v: any) => {
  emit("update:value", v);
};

const { zMessage } = useMessage();

const img = ref<Picture | null>(null);
watchEffect(async () => {
  if (!props.value) {
    img.value = null;
  } else {
    const pict = await getPictureById(props.value);
    img.value = pict;
  }
});

const inputRef = ref();
function trigger() {
  inputRef.value.click();
}
async function fileHandler(event: any) {
  let pict = null;
  if (event.target.files) {
    pict = await pictureUpload({
      file: event.target.files[0],
      type: props.type,
    }).finally(() => {
      inputRef.value.value = null;
    });
  } else {
    zMessage.warning("什么都没选中哦");
  }
  updateValue(pict?.id ?? null);
}
</script>

<style scoped lang="scss">
.container {
  width: v-bind(sizePx);
  height: v-bind(sizePx);
  border: 1px dashed #ccc;

  .trigger {
    --bar-width: 20px;

    width: 100%;
    height: 100%;

    position: relative;
    cursor: pointer;
    .bar {
      height: var(--bar-width);
      width: 80%;
      background-color: #ccc;
      position: absolute;
      top: calc(50% - var(--bar-width) / 2);
      left: 10%;
    }
    .vertical {
      transform: rotate(90deg);
    }
  }
}
</style>
